import os
import smtplib
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from flask import current_app

from apps.interface.util.email.mail_config import EMAIL_SERVICE, EMAIL_PORT


class CheckPath(object):
    def __init__(self, file):
        self.file = file
        # 获取工程目录

    def read_superior_path(self):
        path = os.getcwd()
        parent_path = os.path.dirname(path)
        path_data_conf = parent_path + self.file
        if not (os.path.exists(path_data_conf)):
            current_app.logger.error("请检查是否存在 : {}".format(path_data_conf))
        return path_data_conf


class SendEmail(object):
    def __init__(self, username, password, to_list, file):
        self.Email_service = EMAIL_SERVICE
        self.Email_port = EMAIL_PORT
        self.username = username
        self.password = password
        self.to_list = to_list
        self.file = file

    def send_email(self, name=None, content=None):
        # 第三方 SMTP 服务
        current_app.logger.info('{}-开始发送邮件报告'.format(name))
        message = MIMEMultipart()
        msg_body = SendEmail.get_html_msg(name, content)
        part = MIMEText(msg_body, 'html', 'utf-8'.format(name))
        # 执行时间 用例通过数，用例失败数，接口通过数，接口失败数
        message.attach(part)
        message['From'] = Header("".join(self.username), 'utf-8')
        message['To'] = Header(''.join(self.to_list), 'utf-8')
        subject = '{}-接口测试邮件'.format(name)
        message['Subject'] = Header(subject, 'utf-8')
        # 添加附件
        file_attach = MIMEApplication(open(self.file, 'rb').read())
        file_attach.add_header('Content-Disposition', 'attachment', filename=('gbk', '', '{}-接口测试报告.html'.format(name)))
        message.attach(file_attach)
        try:
            service = smtplib.SMTP_SSL(self.Email_service, self.Email_port)
            service.login(self.username, self.password)
            service.sendmail(self.username, self.to_list, message.as_string())
            service.close()
            current_app.logger.info('{}-发送邮件报告成功'.format(name))
        except Exception as e:
            current_app.logger.error('发送邮件失败了{}'.format(str(e)))

    @classmethod
    def get_html_msg(cls, name, content):
        data = content['stat']
        header = '''<html><body> <style> table,table tr th, table tr td { border:1px solid #0c0c0c; } table { width: 
        600px; min-height: 25px; line-height: 25px; text-align: center; border-collapse: collapse; padding:2px;}
        hr{width: 600px; float: left;} .tc-clean {clear:both;}
         .tc-success {color:rgb(103, 194, 58)} .tc-fail {color:rgb(255, 74, 74)}</style>'''
        body = '''<p>Dear all:\n       附件为{p_name}-接口自动化测试报告，此为自动发送邮件，请勿回复，谢谢！</p>
        <div><span>测试项目: {p_name} 时间: 2020-04-20</span> 
        <table><tr><th>用例总数</th><th>通过</th><th>失败</th><th>通过率</th></tr>
        <tr><td>{case_count}</td><td class="tc-success">{case_pass}</td>
        <td class='tc-fail'>{case_fail}</td><td>{case}</td></tr></table>
        <hr /><div class="tc-clean"></div>
        <table>
        <tr><th>接口总数</th><th>通过</th><th>失败</th><th>通过率</th></tr> 
        <tr><td>{api_count}</td><td class="tc-success">{api_pass}</td><td class="tc-fail">{api_fail}</td>
        <td>{api}</td></tr></table></div>
        <p>详细请见附件</p>
        </body></html>'''.format(p_name=name, case_count=data['all_scene'], case_pass=data['successes_scene'],
                                 case_fail=data['failures_scene'], case=data['successes_scene1'],
                                 api_count=data['testsRun'],
                                 api_pass=data['successes_1'],
                                 api_fail=data['failures_1'], api=data['successes'])
        return header + body
